/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import prompt from '@system.prompt';
import router from '@system.router';
import http from '@ohos.net.http';
const qrcode = {
    id: 1,
    imgUrl: 'common/images/personPic/1.png',
    text: '群二维码',
    url: '',
    find_right_icon: '/common/images/findPic/find-right-icon.png'
}
const Gtalk = [
    {
        id: 1,
        imgUrl: 'common/images/personPic/1.png',
        text: '查找聊天记录',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
    {
        id: 2,
        imgUrl: '/common/images/personPic/2.png',
        text: '消息免打扰',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
    {
        id: 3,
        imgUrl: '/common/images/personPic/3.png',
        text: '置顶聊天',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
    {
        id: 4,
        imgUrl: '/common/images/personPic/4.png',
        text: '提醒',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
    {
        id: 5,
        imgUrl: '/common/images/personPic/5.png',
        text: '设置当前聊天背景',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
    {
        id: 6,
        imgUrl: '/common/images/personPic/5.png',
        text: '清空聊天记录',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
];
const avatar = [
    {
        type:'user',
        imgUrl:'/common/images/sessionPic/img_1.png',
        title:'小蔡'
    },
    {
        type:'buttonAdd',
        imgUrl:'/common/images/addChatFriend.png',
        title:''
    }
];
export default {
    data: {
        GtalkList: Gtalk,
        qr:qrcode,
        avatarList: avatar,
        checkedId: [],
        checkedUid: [],
        groupName:'',
        groupId:'',
        re:{
            code:"",
            msg:"",
            data:""
        },
        testId:'',
        sayOrGroup:'',
        sayOrGroup_ID:'',
        isTalkForbidden: false,
        userGroupNickname: '',
    },
    onInit() {
        if(this.sayOrGroup == 'group'){
            this.getGroupMembers();
            this.getUserGroupNickname();
            //            this.sayOrGroup==router.getParams().sayOrGroup
            this.sayOrGroup = "group"
            this.isTalkForbidden=router.getParams().isTalkForbidden
        }
        this.avatarList[0].imgUrl = this.$app.$def.chatData[this.$app.$def.idx].imgUrl;
        this.avatarList[0].title = this.$app.$def.chatData[this.$app.$def.idx].title;
        //        this.friendsList = this.$app.$def.friendsList
    },
    onShow() {
        this.getUserGroupNickname();
        this.groupId = this.getRandomSixDigit()
        let typec=router.getParams().sayOrGroup
//        let typec="group"
        if(typec){
            this.sayOrGroup = typec
        }
        this.sayOrGroup_ID=router.getParams().sayOrGroup_ID
        console.info('chatMessagePage====sayOrGroup:' + this.sayOrGroup)
        console.info('chatMessagePage====sayOrGroup_ID:' + this.sayOrGroup_ID)
    },
    backToSession(){
        router.back();
    },
    change(e){
        this.groupName = e.value;
    },
    getRandomSixDigit(){
        let code = ''
        for(var i=0;i<6;i++){
            code += parseInt(Math.random()*10)
        }
        return code
    },
    dismiss() {
        //todo 测试dimiss this.sayOrGroup_ID
        console.info('chatMessagePage====dismiss:' + this.sayOrGroup_ID)
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/disband/" + this.sayOrGroup_ID, {
            method: 'POST',
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString())
            console.info('chatMessagePage====>disband:'+re)
            if(re.code == 2027) {
                prompt.showToast({
                    message: '解散成功',
                    duration: 2000,
                });
                router.push({
                    uri:'pages/sessionList/sessionList'
                })
            } else if(re.code == 2028) {
                prompt.showToast({
                    message: '解散失败',
                    duration: 2000,
                });
            }
        }).catch((err) => {
            console.error(`chatMessagePage====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    toQrCode(){
        router.push({
            uri: "pages/myList/qrcode/qr",
            params: {
                sayOrGroup: 'group',
                sayOrGroup_ID: this.sayOrGroup_ID,
            },
        });
    },
    intoDetails(type){
        // 这个页面，个人、群组公用，当sayOrGroup等于group的时候，跳转"邀请群成员加入"页面。
        if(type == 'buttonAdd') {
            if (this.sayOrGroup == 'group') {
                router.push({
                    uri: "pages/createGroup/createGroup",
                    params: {
                        operation: 'invite',
                        groupId: this.sayOrGroup_ID,
                    },
                });
            } else if (this.sayOrGroup == 'say') {
                router.push({
                    uri: "pages/createGroup/createGroup",
                    params: {
                        operation: 'create',
                    },
                });
            }
        }else if(type == 'buttonDelete'){
            router.push({
                uri: "pages/createGroup/createGroup",
                params: {
                    operation: 'delete',
                    groupId: this.sayOrGroup_ID,
                },
            });
        }
    },
    getGroupMembers() {
        // console.info('createGroup====> getGroupMembers :' + this.$app.$def.uid)
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/groupMembersList/" + this.groupId, {
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            this.re  = JSON.parse(value.result.toString())
            let re = this.re;
            console.info('createGroup====> re: '+re)
            if(re.code == 200) {
                this.$app.$def.groupMembersList = []
                for (let i = 0; i < re.data.length; i++) {
                    let groupMember = {
                        id: re.data[i],
                        imgUrl: '/common/images/sessionPic/img_' + Math.round(Math.random()*7+1) + '.png',
                        text: re.data[i],
                        url: '',
                        style: 'pengyou'
                    }
                    this.$app.$def.groupMembersList.push(groupMember)
                }
            }
        }).catch((err) => {
            console.error(`createGroup====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    groupForbiddenSwitch(e){
        console.log(e.checked);
        if(e.checked){
            // 设置群禁言
            //        TODO  未完成
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/forbidTalk", {
                method: 'POST',
                extraData:JSON.stringify({"uid":this.$app.$def.uid, "groupId":this.groupId}),
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((value) => {
                let re = JSON.parse(value.result.toString())
                if(re.code == 2039){
                    prompt.showToast({
                        message: "禁言群组成功"
                    });
                } else if(re.code == 2040){
                    prompt.showToast({
                        message: "禁言群组失败"
                    });
                }
            }).catch((err) => {
                console.error(`groupForbiddenSwitch====> errCode:${err.code}, errMessage1:${err.data}`);
            });
        }else{
            // 取消群禁言
            //        TODO  未完成
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/cancelForbid", {
                method: 'POST',
                extraData:JSON.stringify({"uid":this.$app.$def.uid, "groupId":this.groupId}),
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((value) => {
                let re = JSON.parse(value.result.toString())
                if(re.code == 2043){
                    prompt.showToast({
                        message: "取消群组禁言成功"
                    });
                } else if(re.code == 2040){
                    prompt.showToast({
                        message: "取消群组禁言失败"
                    });
                }
            }).catch((err) => {
                console.error(`groupForbiddenSwitch====> errCode:${err.code}, errMessage1:${err.data}`);
            });
        }
    },
    getUserGroupNickname() {
        let httpRequest = http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/getUserGroupNickname", {
            method: 'POST',
            extraData:JSON.stringify({"uid":this.$app.$def.uid, "groupId":this.sayOrGroup_ID}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString())
            if(re.code == 200){
                prompt.showToast({
                    message: "获取用户群昵称成功"
                });
                console.info("chatMessagePage=====getUserGroupNickname re.data : " + re.data);
                this.userGroupNickname = re.data;
            } else {
                prompt.showToast({
                    message: "获取用户群昵称失败"
                });
            }
        }).catch((err) => {
            console.error(`chatMessagePage====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    clickNickname() {
        router.push({
            uri: "pages/dialogPage/chatMessagePage/changeUserGroupNickname/changeUserGroupNickname",
            params: {
                groupId: this.sayOrGroup_ID,
            },
        });
    },
}